//
//  RNOLMyBackRefundCalendarViewController.m
//  RongNiuOnline
//
//  Created by apple on 2018/4/27.
//  Copyright © 2018年 rongniu. All rights reserved.
//

#import "RNOLMyBackRefundCalendarViewController.h"
#import "RNOLInvestCalendarHeader.h"
#import "RNOLReturnMoneyCalendarMarkView.h"

@interface RNOLMyBackRefundCalendarViewController ()<UITableViewDelegate,UITableViewDataSource,FSCalendarDataSource,FSCalendarDelegate,UIGestureRecognizerDelegate,FSCalendarDelegateAppearance>

@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) FSCalendar *calendar ;
@property (strong, nonatomic) NSCalendar *gregorian;

@property (strong, nonatomic) NSDateFormatter *dateFormatter;
@property (strong, nonatomic) UIPanGestureRecognizer *scopeGesture;

@property (strong, nonatomic) NSArray *datesWithEvent;
@property (strong, nonatomic) NSArray *datesWithEvent002;
@property (strong, nonatomic) NSArray *datesWithMultipleEvents;

@property (nonatomic,strong) RNOLInvestCalendarHeader *calendarHeader;

@end


@implementation RNOLMyBackRefundCalendarViewController

- (FSCalendar *)calendar{
    if (!_calendar) {
        _calendar = [[FSCalendar alloc] init];
        _calendar.scope = FSCalendarScopeMonth;
        _calendar.placeholderType =  FSCalendarPlaceholderTypeNone;
        _calendar.calendarHeaderView.hidden = YES;
        _calendar.appearance.weekdayTextColor = kTextColor;
        _calendar.appearance.selectionColor = kAppMainColor;
        _calendar.appearance.titleTodayColor = kTextColor;
//        _calendar.today = nil;//今天不要圆圈
        _calendar.backgroundColor = KWhiteColor;
        _calendar.delegate = self;
        _calendar.dataSource = self;
        [self.view addSubview:_calendar];
    }
    return _calendar;
}


- (UITableView *)tableView{
    if(!_tableView){
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.backgroundColor = kBgColor;
        adjustsScrollViewInsets_NO(_tableView, self);
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.rowHeight = 60;
        UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0 , 0.01)];
        _tableView.tableHeaderView = header;
        _tableView.tableFooterView = [UIView new];
        [self.view addSubview: _tableView];
    }
    return _tableView;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = KWhiteColor;
    [self setupNavBarTitleViewWithText:@"回款日历"];
    [self initConfig];
    [self setup];
}

- (void)initConfig{
    self.dateFormatter = [[NSDateFormatter alloc] init];
    self.dateFormatter.dateFormat = @"yyyy/MM/dd";
    [self.calendar selectDate:[NSDate date] scrollToDate:YES];
    self.gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    
    UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget: self.calendar action:@selector(handleScopeGesture:)];
    panGesture.delegate = self;
    panGesture.minimumNumberOfTouches = 1;
    panGesture.maximumNumberOfTouches = 2;
    [self.view addGestureRecognizer:panGesture];
    self.scopeGesture = panGesture;
    [self.tableView.panGestureRecognizer requireGestureRecognizerToFail:panGesture];
    
    self.datesWithEvent = @[@"2018/05/03",
                            @"2018/05/04",
                            @"2018/05/05",
                            @"2018/05/06"];
    
    self.datesWithEvent002 = @[@"2018/05/07",
                               @"2018/05/08",
                               @"2018/05/09",
                               @"2018/05/10"];
    
    self.datesWithMultipleEvents = @[@"2018/05/13",
                                     @"2018/05/14",
                                     @"2018/05/15",
                                     @"2018/05/17"];

}


- (void)setup{
    UIView *headerBg = [RNOLUnitTool createViewWithBackgroundColor: KWhiteColor];
    headerBg.frame = CGRectMake(0, 30, KWIDTH , 40);
    headerBg.userInteractionEnabled = YES;
    [self.view addSubview: headerBg];
    RNOLInvestCalendarHeader *header = [RNOLInvestCalendarHeader FromXIB];
    header.frame = headerBg.bounds;
    [headerBg addSubview: header];
    self.calendarHeader = header;

    [self.calendar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@280);
        make.left.right.equalTo(@0);
        make.top.equalTo(@31);
    }];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.calendar.mas_bottom).offset(0);
        make.left.right.bottom.equalTo(self.view);
    }];
    
    [self updateDateActionEvents];
}


#pragma mark- 刷新日历视图
- (void)updateDateActionEvents{
    @weakify(self);
    [self updateHeaderDisplay];
    [self.calendarHeader setLastMonthBlock:^{//上一个月
        @strongify(self);
        NSDate *currentMonth = self.calendar.currentPage;
        NSDate *previousMonth = [self.gregorian dateByAddingUnit:NSCalendarUnitMonth value:-1 toDate:currentMonth options:0];
        [self.calendar setCurrentPage:previousMonth animated:YES];
    }];
    
    [self.calendarHeader setNextMonthBlock:^{//下一个月
        @strongify(self);
        NSDate *currentMonth = self.calendar.currentPage;
        NSDate *nextMonth = [self.gregorian dateByAddingUnit:NSCalendarUnitMonth value:1 toDate:currentMonth options:0];
        [self.calendar setCurrentPage:nextMonth animated:YES];
    }];
    
    [self.calendarHeader setSelectDateBlock:^{//选择某一个月份
       @strongify(self);
        [WGBDatePickerView showPickerViewWithPickerDateBlock:^(NSDate *date) {
            [self.calendar setCurrentPage: date animated:YES];
        }];
    }];
}

- (void)dealloc{
    NSLog(@"%s",__FUNCTION__);
}

#pragma mark- 更新头部的显示
- (void)updateHeaderDisplay{
    NSDate *currentMonth = self.calendar.currentPage;
    NSString *totalStr = [NSString stringWithFormat:@"%02ld月 %ld ▼",currentMonth.month,currentMonth.year];
    NSMutableAttributedString *attributeStr = [RNOLUnitTool wgb_changeFontAndColor:KFontSize(20) Color:kTextColor TotalString:totalStr SubStringArray:@[kWGB_STR(@"%02ld月",currentMonth.month)]];
     self.calendarHeader.dateLabel.attributedText = attributeStr;
}


#pragma mark -  UITableViewDelegate && UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 20;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    cell.textLabel.text = @(indexPath.row).stringValue;
    cell.textLabel.textColor = kTextColor;
    cell.textLabel.font = KFontSize(15);
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 110;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headerBg = [RNOLUnitTool createViewWithBackgroundColor: kBgColor];
    headerBg.frame = CGRectMake(0,0, KWIDTH , 110);
    RNOLReturnMoneyCalendarMarkView *header = [RNOLReturnMoneyCalendarMarkView FromXIB];
    header.frame = CGRectMake(0, 10, KWIDTH , 90);
    [headerBg addSubview: header];
    return headerBg;
}


- (void)viewDidLayoutSubviews
{
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsMake(0,0,0,0)];
    }
    
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.tableView setLayoutMargins:UIEdgeInsetsMake(0,0,0,0)];
    }
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0) {
        FSCalendarScope selectedScope = indexPath.row == 0 ? FSCalendarScopeMonth : FSCalendarScopeWeek;
        [self.calendar setScope:selectedScope animated: YES];
    }
}


#pragma mark - <UIGestureRecognizerDelegate>

// Whether scope gesture should begin
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
    BOOL shouldBegin = self.tableView.contentOffset.y <= -self.tableView.contentInset.top;
    if (shouldBegin) {
        CGPoint velocity = [self.scopeGesture velocityInView:self.view];
        switch (self.calendar.scope) {
            case FSCalendarScopeMonth:
                return velocity.y < 0;
            case FSCalendarScopeWeek:
                return velocity.y > 0;
        }
    }
    return shouldBegin;
}

#pragma mark - <FSCalendarDelegate>

- (void)calendar:(FSCalendar *)calendar boundingRectWillChange:(CGRect)bounds animated:(BOOL)animated
{
    [self.view needsUpdateConstraints];
    [self.calendar mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@(CGRectGetHeight(bounds)));
        make.left.right.equalTo(@0);
        make.top.equalTo(@31);
    }];
    [self.view layoutIfNeeded];
}

- (void)calendar:(FSCalendar *)calendar didSelectDate:(NSDate *)date atMonthPosition:(FSCalendarMonthPosition)monthPosition
{
    NSLog(@"did select date %@",[self.dateFormatter stringFromDate:date]);
    if (monthPosition == FSCalendarMonthPositionNext || monthPosition == FSCalendarMonthPositionPrevious) {
        [calendar setCurrentPage:date animated:YES];
    }
}

- (void)calendarCurrentPageDidChange:(FSCalendar *)calendar{
    [self updateHeaderDisplay];
}

#pragma mark - <FSCalendarDataSource>
- (NSInteger)calendar:(FSCalendar *)calendar numberOfEventsForDate:(NSDate *)date{
    NSString *dateString = [self.dateFormatter stringFromDate:date]; //日期格式
    if ([self.datesWithEvent containsObject:dateString]) { //日期返回一个点的
        return 1;
    }
    if ([self.datesWithEvent002 containsObject: dateString]) {
        return 1;
    }
    if ([self.datesWithMultipleEvents containsObject:dateString]) {//返回三个点的
        return 2;
    }
    return 0;
}

- (NSDate *)minimumDateForCalendar:(FSCalendar *)calendar
{
    return [self.dateFormatter dateFromString:@"2017-05-01"];
}

- (NSDate *)maximumDateForCalendar:(FSCalendar *)calendar
{
    return [[NSDate date] dateByAddingDays: 365*3];
}

- (NSString *)calendar:(FSCalendar *)calendar titleForDate:(NSDate *)date
{
    NSDate *currentDate = [NSDate date];
    if (currentDate.day == date.day && currentDate.month == date.month&&currentDate.year == date.year) {
        return @"今";
    }
    return nil;
}

#pragma mark - <FSCalendarDelegateAppearance>
- (NSArray *)calendar:(FSCalendar *)calendar appearance:(FSCalendarAppearance *)appearance eventDefaultColorsForDate:(NSDate *)date{
    NSString *dateString = [self.dateFormatter stringFromDate:date];
    if ([_datesWithMultipleEvents containsObject:dateString]) {
        return @[kAppMainColor,kAssistRedColor];
    }
    if ([_datesWithEvent002 containsObject: dateString]) {
        return @[kAppMainColor];
    }
    if ([_datesWithEvent containsObject: dateString]) {
        return @[kAssistRedColor];
    }
    return nil;
}


@end
